import { remove, getList, save, GetParentSetting, ParentSetting } from '@/api/maint/dingDing'
import permission from '@/directive/permission/index.js'
import { getall as getUser } from '@/api/usr/user'
import { getall as getDept } from '@/api/usr/dept'

export default {
  directives: { permission },
  data() {
    return {
      formVisible: false,
      formTitle: '编辑钉钉',


      settingFormVisible: false,
      settingFormTitle: '添加钉钉配置',
      deptList: [],
      roleList: [],
      WeChatUsers: [],
      isAdd: true,
      checkedPermissionKeys: [],
      permissons: [],
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children'
      },
      permissonVisible: false,
      settingForm: {
        id: null,
        isPid: true,
        appkey: '',
        appsecret: '',
        agent_id: '',
        defaultTimer: 0,
        defaultTimerInterval: 3600,
        to_All_User: false,
        description: '',
      },
      form: {
        id: null,
        name: '',
        pId: null,
        isPid: false,
        userId_List: '',
        dept_Id_List: '',
        to_All_User: false,
        msgtype: 'text',
        agentid: '',
        title: '',
        content: '',
        description: '',
      },
      showToParty: true,
      settingFormRules: {
        appkey: [
          { required: true, message: '请输入appkey', trigger: 'blur' },
        ],
        appsecret: [
          { required: true, message: '请输入appsecret', trigger: 'blur' },
        ],
        agent_id: [
          { required: true, message: '请输入agent_id', trigger: 'blur' },
        ],
        defaultTimerInterval: [
          { required: true, message: '请输入定时器间隔时间', trigger: 'blur' },
        ],

      },
      formRules: {
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入模板内容', trigger: 'blur' },
        ],
        title: [
          { required: true, message: '请输入模板标题', trigger: 'blur' },
        ],

      },
      listQuery: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined
      },
      total: 0,
      deptId: [],
      list: null,
      listLoading: true,
      selRow: {},
      allUserWeChat: {},
      allCurrentState: {},
      allDept: {},
      sort: { prop: 'name', order: 'descending' }
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getList(this.listQuery).then(data => {
        this.list = data.data
        this.listLoading = false
        this.total = data.totalCount
      })
    },
    search() {
      this.fetchData()
    },
    reset() {
      this.listQuery.name = ''
      this.fetchData()
    },
    handleFilter() {
      this.getList()
    },
    fetchNext() {
      this.listQuery.pageIndex = this.listQuery.pageIndex + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.pageIndex = this.listQuery.pageIndex - 1
      this.fetchData()
    },
    fetchPage(pageIndex) {
      this.listQuery.pageIndex = pageIndex
      this.fetchData()
    },
    changeSize(pageSize) {
      this.listQuery.pageSize = pageSize
      this.fetchData()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRow = currentRow
      //console.log(currentRow)
    },
    initGetUserChat() {
      getUser().then(response => {
        var users = []
        response.forEach(element => {
          if (element.dingDing != '' && element.dingDing != null)
            users.push({ id: Symbol(element.dingDing), dingDing: element.dingDing, deptId: element.deptId })
        });
        this.allUserWeChat = users
        console.log(this.allUserWeChat)
      })
    },
    initDept() {
      getDept().then(res => {


        this.allDept = res
        //this.allDept = this.convertToTreeData(res)
        console.log(this.allDept)
      })
    },

    resetForm() {

      this.settingForm = {
        id: null,
        isPid: true,
        appkey: '',
        appsecret: '',
        agent_id: '',
        defaultTimer: 0,
        defaultTimerInterval: 3600,
        to_All_User: false,
        description: '',
      },
        this.form = {
          id: '',
          name: '',
          pId: null,
          isPid: false,
          userId_List: '',
          dept_Id_List: '',
          to_All_User: false,
          msgtype: 'text',
          agentid: '',
          title: '',
          content: '',
          description: '',
        }
    },

    settingFrom() {
      this.resetForm()
      GetParentSetting().then(data => {
        console.log(data)
        if (data == null) {

          this.settingFormVisible = true
          this.settingFormTitle='添加钉钉配置'

          this.isAdd = true
        } else {
          this.settingForm.id = data.id
          this.settingForm.appkey = data.appkey
          this.settingForm.appsecret = data.appsecret
          this.settingForm.agent_id = data.agent_id
          this.settingForm.defaultTimer = data.defaultTimer
          this.settingForm.defaultTimerInterval = data.defaultTimerInterval
          this.settingForm.description = data.description
          this.settingFormVisible = true
          this.settingFormTitle='编辑钉钉配置'
          this.isAdd = false
        }
      })

    },

    settingSave() {
      this.$refs['settingForm'].validate((valid) => {
        if (valid) {
          console.log(this.settingForm)
          ParentSetting({
            id: this.settingForm.id,
            appkey: this.settingForm.appkey,
            appsecret: this.settingForm.appsecret,
            agent_id: this.settingForm.agent_id,
            defaultTimer: this.settingForm.defaultTimer,
            defaultTimerInterval: this.settingForm.defaultTimerInterval,
            to_All_User: this.settingForm.to_All_User,
            description: this.settingForm.description,

          }).then(response => {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.fetchData()
            this.settingFormVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })

    },
    Save() {
      if (this.form.userId_List == '' && this.form.dept_Id_List == '') {
        this.$message({
          message: '请选择成员或者部门',
          type: 'warning'
        })
        return false
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            save({
              id: this.form.id,
              name: this.form.name,
              pId: this.form.pId,
              isPid: false,
              userId_List: this.form.userId_List,
              dept_Id_List: this.form.dept_Id_List,
              to_All_User: this.form.to_All_User,
              title: this.form.title,
              msgtype: this.form.msgtype,

              content: this.form.content,
              description: this.form.description,
            }).then(response => {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.fetchData()
              this.formVisible = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }


    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true
      }
      this.$message({
        message: '请选中操作项',
        type: 'warning'
      })
      return false
    },
    Cancel() {
      this.formVisible = false
      this.resetForm()

    },
    add() {
      this.resetForm()
      this.initGetUserChat()
      this.initDept()

      this.WeChatUsers = []
      this.formVisible = true
      this.formTitle = '添加模板'
      this.isAdd = true
      this.showToParty = true
    },

    edit(row) {
      console.log(row)
      this.initDept()
      this.resetForm()
      this.initGetUserChat()
      this.handleCurrentChange(row)

      if (this.checkSel()) {
        this.isAdd = false
        // this.form = this.selRow
        this.form.id = row.id
        this.form.name = row.name
        this.form.pId = row.pId
        this.form.userId_List = row.userId_List
        this.form.to_All_User = row.to_All_User
        this.form.dept_Id_List = row.dept_Id_List
        this.form.title = row.title

        this.form.content = row.content
        this.form.description = row.description
        this.WeChatUsers = []

        this.deptId = []
        var str = row.userId_List;
        if (str != '') {
          var list = str.split("|");

          list.forEach(item => {
            //this.WeChatUsers.push(element)
            this.WeChatUsers.push(item)

          })
        }

        var part = row.dept_Id_List;
        if (part != '') {
          var listPart = part.split("|");

          listPart.forEach(item => {
            //this.WeChatUsers.push(element)
            this.deptId.push(item)

          })
        }



       

        this.formTitle = '修改模板'
        //this.form.disabledPwd=true
        this.formVisible = true
      }

    },
    selectWeChatUser(res) {
      var touser = '';
      this.showToParty = true
      res.forEach(element => {

        touser += element + ","
      });
      // let index = res.indexOf('@all');
      // if (index === -1) {
      //   this.showToParty = true
      // } else {
      //   this.showToParty = false
      //   this.form.totag = '@all'
      //   this.form.toparty = '@all'

      // }
      this.form.userId_List = touser.substring(0, touser.length - 1)

    },
    selectDept(data) {

      var dept = ''
      console.log(data)
      data.forEach(res => {
        dept += res + "|"
      })
      dept = dept.substring(0, dept.length - 1)
      this.form.dept_Id_List = dept
    },
    remove(row) {
      this.handleCurrentChange(row)
      if (this.checkSel()) {
        const id = row.id
        this.$confirm('确定删除消息以及参数和模板?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          remove(id).then(response => {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.fetchData()
          }).catch(err => {
            this.$notify.error({
              title: '错误',
              message: err
            })
          })
        }).catch(() => {
        })
      }
    },
    componentTips() {
      this.$notify({
        title: '提示',
        dangerouslyUseHTMLString: true,
        message: '{AccountName}: 用户账号<br/>{ReminderTime}: 提醒时间<br/>{Hour}: 还有几个小时过期<br/>{WebsiteUrl}: 提醒的网址<br/>如:你的账号{AccountName}将在{ReminderTime}还有{Hour}小时过期请前往{WebsiteUrl}及时修改过期时间'
      })
    },
    flexWidth(prop, tableData, title, num = 0) {
      if (tableData === null || tableData.length === 0) {//表格没数据不做处理
        return;
      }
      //console.log(tableData)
      let flexWidth = 0;//初始化表格列宽
      let columnContent = '';//占位最宽的内容
      let canvas = document.createElement("canvas");
      let context = canvas.getContext("2d");
      context.font = "14px Microsoft YaHei";
      if ((prop === '') && title) {//标题长内容少的，取标题的值,
        columnContent = title
      } else {// 获取该列中占位最宽的内容
        let index = 0;
        for (let i = 0; i < tableData.length; i++) {
          const now_temp = tableData[i][prop] + '';
          const max_temp = tableData[index][prop] + '';
          const now_temp_w = context.measureText(now_temp).width
          const max_temp_w = context.measureText(max_temp).width
          if (now_temp_w > max_temp_w) {
            index = i;
          }
        }
        columnContent = tableData[index][prop]
        //比较占位最宽的值跟标题、标题为空的留出四个位置
        const column_w = context.measureText(columnContent).width
        const title_w = context.measureText(title).width
        if (column_w < title_w) {
          columnContent = title || '留四个字'
        }
      }
      // 计算最宽内容的列宽
      let width = context.measureText(columnContent);
      flexWidth = width.width + 80 + num
      return flexWidth + 'px';
    },
  }
}
